// 日志处理
package illusion

import (
	"os"
	"strings"
	"time"
	//	"sync"
	//"fmt"
	"log"
	"path/filepath"
	//"sync"
	"sync"
	"fmt"
)
var il  *log.Logger
var im sync.Mutex
var iOnce sync.Once = sync.Once{}
//通过设置返回对应的logger对象

func setLogger(basePath string) {
	iOnce.Do(func(){
		im = sync.Mutex{}
	})
	im.Lock()
	handler := findTodayLogFile(basePath)
	il = log.New(handler, "", log.LstdFlags)
	il.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
	im.Unlock()
}
func Logger() *log.Logger {
	if il == nil {
		panic("请设置logger")
	}
	return il
}

func findTodayLogFile(relativePath string) *os.File {
	basePath := string(filepath.Separator) + strings.TrimPrefix(relativePath, "/")
	absPath, _ := filepath.Abs(".")
	fullPathToTodayFile := absPath + basePath + string(filepath.Separator) + strings.Split(time.Now().Format("2006-01-02 15:04:05"), " ")[0] + ".log"
	handler, err := os.OpenFile(fullPathToTodayFile, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
	if err != nil { //直接退出程序
		fmt.Println("创建日志文件失败:" + err.Error())
		os.Exit(0)
	}
	return handler
}
